
const container = document.getElementById('ml_chancel_container');
const item = document.getElementById('ml_chancel_temp');
const slider_time = document.getElementById('ml_us_range');
const input_time = document.getElementById('ml_us_input');
const input_us_number = document.getElementById('ml_us_number');
const ml_us_select = document.getElementById('ml_us_select');
const xAxis_select = document.getElementById('xAxis');
const yAxis_select = document.getElementById('yAxis');

let ch_list = [];

document.addEventListener('DOMContentLoaded', function () {
    changeTime();
    selectCHForTime();
    moveTo();
    selectCHForControl();
    selectControl();
    selectXY();
    loadModel();
});

function changeTime() {
    // 监听 range 输入框的变化
    slider_time.addEventListener('input', function () {
        // 更新 text 输入框的值
        input_time.value = `${slider_time.value}us`;
    });

    // 监听 text 输入框的变化
    input_time.addEventListener('input', function () {
        const value = input_time.value.replace('us', ''); // 移除单位
        if (!isNaN(value) && value >= slider_time.min && value <= slider_time.max) {
            // 更新 range 输入框的值
            slider_time.value = value;
        }
    });

    //输入框失去焦点时触发
    input_time.addEventListener('blur', function () {
        input_time.value = input_time.value + 'us';
    });
}

function selectCHForTime() {
    // 获取所有 checkbox 元素
    const checkboxes = document.querySelectorAll('.ml_ch_list input[type="checkbox"]');

    checkboxes.forEach((checkbox, index) => {
        // 为每个 checkbox 添加 change 事件监听器
        checkbox.addEventListener('change', function () {
            var a = `Checkbox ${index + 1} is ${checkbox.checked ? 'checked' : 'unchecked'}`;
            console.log(`${a}`)
            alert(`${a}`);
        });
    });
}

function moveTo() {
    // 监听输入框变化
    input_us_number.addEventListener('input', function () {
        // 根据输入框的值设置下拉框选中的选项
        let inputValue = input_us_number.value;
        if (inputValue <= 1) {
            ml_us_select.value = "1";  // 设置为 "us"
        } else if (inputValue <= 2) {
            ml_us_select.value = "2";  // 设置为 "us-1"
        } else if (inputValue <= 3) {
            ml_us_select.value = "3";  // 设置为 "us-2"
        } else {
            ml_us_select.value = "4";  // 设置为 "us-3"
        }
    });

    // 监听下拉框变化
    ml_us_select.addEventListener('change', function () {
        // 根据选中的下拉选项设置输入框的值
        let selectedValue = ml_us_select.value;
        if (selectedValue == "1") {
            input_us_number.value = 1;
        } else if (selectedValue == "2") {
            input_us_number.value = 2;
        } else if (selectedValue == "3") {
            input_us_number.value = 3;
        } else {
            input_us_number.value = 4;
        }
    });
}

function selectCHForControl() {
    const radios = document.querySelectorAll('.ml_ch_list input[type="radio"]');

    radios.forEach((radio, index) => {
        // 为每个 checkbox 添加 change 事件监听器
        radio.addEventListener('change', function () {
            var a = `Radio ${index + 1} is ${radio.checked ? 'checked' : 'unchecked'}`;
            console.log(`${a}`)
            alert(`${a}`);
        });
    });
}

function selectControl() {
    const checkboxes = document.querySelectorAll('.ml_direction_list input[type="checkbox"]');

    checkboxes.forEach((checkbox, index) => {
        // 为每个 checkbox 添加 change 事件监听器
        checkbox.addEventListener('change', function () {
            var a = `Checkbox ${index + 1} is ${checkbox.checked ? 'checked' : 'unchecked'}`;
            console.log(`${a}`)
            alert(`${a}`);
        });
    });
}

function selectXY() {
    xAxis_select.addEventListener('change', function () {
        var a = `x移动至 ${xAxis_select.value}`;
        console.log(`${a}`)
        alert(`${a}`);
    });
    yAxis_select.addEventListener('change', function () {
        var a = `y移动至 ${yAxis_select.value}`;
        console.log(`${a}`)
        alert(`${a}`);
    });
}

// 监听颜色选择结果
MyAPI.onColorPicked((event, color, indexElementId, index) => {
    ch_list[index].color = `${color}`;
    document.getElementById(`${indexElementId}`).style.backgroundColor = color;// 更新颜色按钮的背景色
    updateChannelModel(ch_list[index]);
});

// 监听错误
MyAPI.onColorPickError((event, error, ch, index) => {
    console.error('Error picking color:', error, ch);
    // alert(error); // 提示错误信息
});

///监听信号选择
MyAPI.listenSignalSelect((event, ch) => {
    const index = ch_list.findIndex((item) => item.id === ch.id);
    if (index !== -1) {
        ch_list[index] = ch;
        updateChannelModel(ch_list[index]);
        loadModel();
    }
});

///动态加载子元素
function loadChannelItems() {

    // 清空容器
    container.innerHTML = '';
    // 循环生成多个通道项
    for (let i = 1; i <= ch_list.length; i++) {
        const ch = ch_list[i - 1];
        // 克隆模板
        const clone = document.importNode(item.content, true);

        // 获取克隆的元素
        const indexElement = clone.querySelector('.ml_chancel_item_index');
        const elementTitle = clone.querySelector('.ml_chancel_item_left_title');
        const colorPicker = clone.querySelector('input[type="color"]');
        const slider = clone.querySelector('input[type="range"]');
        const button = clone.querySelector('.ml_chancel_item_right button');
        const selectOption = clone.querySelector('select');
        const numberInputs = clone.querySelectorAll('input[type="number"]');

        //1， 更新索引文本和背景颜色
        indexElement.textContent = i;
        indexElement.style.backgroundColor = ch.color;
        indexElement.setAttribute('id', `indexElement${i}`); // 设置 id 属性
        indexElement.addEventListener('click', async function () {
            MyAPI.showColorPicker(`${ch.color}`, `indexElement${i}`, i - 1);
        });

        //2， 设置通道名称
        elementTitle.textContent = `${ch.name}`;


        //3，设置electron颜色选择器的动态 ID 和 label 的关联
        colorPicker.value = ch.color;
        // colorPicker.setAttribute('id', `colorPicker${i}`);
        indexElement.setAttribute('for', `colorPicker${i}`);
        colorPicker.addEventListener("input", async function () {
            ch.color = `${colorPicker.value}`;
            indexElement.style.backgroundColor = colorPicker.value;  // 更新颜色按钮的背景色
            updateChannelModel(ch);
        });

        //4，设置线条宽度ID和值
        slider.min = ch.minWeight;
        slider.max = ch.maxWeight;
        slider.step = ch.stepWeight;
        slider.value = ch.weight;
        slider.setAttribute('id', `weight${i}`);
        slider.addEventListener('input', function () {
            numberInputs[0].value = slider.value;
            ch.weight = slider.value;
            updateChannelModel(ch);
        });

        ///5，设置按钮
        const button_str = ch.signalSelect.replaceAll(',', '');
        button.textContent = button_str.binaryToHexString();
        button.setAttribute('id', `my_signal_btn${i}`);
        button.addEventListener('click', function () {
            //自定义弹窗1 你的按钮点击逻辑
            // document.getElementById('my-dialog').showModal();
            MyAPI.popupWindow('sign_choose.html', 450, 220, ch);
        });

        //6, 监听选择框的变化
        selectOption.value = ch.options;
        selectOption.addEventListener('change', function () {
            ch.options = selectOption.value;
            updateChannelModel(ch);
        });

        //7,输入框
        numberInputs.forEach((element, index) => {
            element.min = index == 0 ? ch.minWeight : 0;
            element.max = index == 0 ? ch.maxWeight : 100;
            element.step = index == 0 ? ch.stepWeight : 1;
            element.value = index == 0 ? ch.weight : ch.inputName;
            element.addEventListener('input', function () {
                if (index == 0) {
                    if (parseFloat(element.value) > parseFloat(element.max) || parseFloat(element.value) < parseFloat(element.min)) {
                        return;
                    }
                    ch.weight = element.value;
                    slider.value = element.value;
                } else {
                    ch.inputName = element.value;
                }
                updateChannelModel(ch);
            });
        });

        // 将克隆的元素添加到容器中
        container.appendChild(clone);
    }
}


///更新通道信息
async function updateChannelModel(ch) {
    const result = await ChannellAPI.updateChannel(ch);
    if (result.success == false) {
        alert(`${result.error}`);
    }
}

async function loadModel() {
    ch_list = await ChannellAPI.getAllChannel;
    // 调用函数，生成 6 个通道项
    loadChannelItems();
}

